package com.kclmedu.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/*************************
 *@ClassName MyFilter
 *@Description TODO
 *@Author yejf
 *@Date 2019-12-01 23:52
 *@Version 1.0
 */
@Component //要做为一个组件被 Spring容器所管理
public class MyFilter extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public String filterType() {
        log.debug("-- 进入了 filterType() 方法, FilterType有4种，分别是： pre, post, routing, error");
        return "pre";
    }

    @Override
    public int filterOrder() {
        log.debug("-- 进入了filterOrder()方法...");
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        log.debug("-- 进入了shouldFilter()方法...,返回true代表要进行过滤");
        return true;
    }

    /****
     * @Author yejf
     * @Description 这个方法是用来制定过滤规则的方法，可以查询sql，正则来过滤
     * @Date 23:56 2019-12-01
     * @param []
     * @return java.lang.Object
     */
    @Override
    public Object run() throws ZuulException {
        log.debug("-- 进入run() 方法...");
        //通过Spring cloud zuul 框架提供的 RequestContext来获取请求
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        //
        String token = request.getParameter("token");
        if(token == null) {
            log.warn("token is empty");
            //
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            //
            try {
                context.getResponse().getWriter().write("token is empty");
            } catch (Exception e) {
                log.error("出错了",e);
                return null;
            }
        }
        //
        log.debug("ok");
        return null;
    }
}
